import { get, post, put, del } from "../../api/request";

Page({
  data: {
    appointmentList: [],
    loading: false,
    noData: false,
    currentPage: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad(options) {
    // 页面加载时初始化数据
    this.getAppointmentList(true);
  },

  onShow() {
    // 每次页面显示时刷新数据
    this.setData({
      currentPage: 1,
      appointmentList: [],
      hasMore: true
    });
    this.getAppointmentList(true);
  },

  // 获取预约列表
  getAppointmentList(showLoading = false) {
    if (this.data.loading || !this.data.hasMore) return;

    if (showLoading) {
      wx.showLoading({
        title: '加载中...',
      });
    }

    this.setData({ loading: true });

    // 调用获取预约列表的API
    get(`/user/reservation_list`).then(res => {
      wx.hideLoading();
      console.log('预约申请列表', res);
      if (res && res.code === 200) {
        const newList = res.data || [];
        const total = newList.length || 0;

        // 处理预约状态和日期格式化
        const formattedList = newList.map(item => {
          // 格式化状态显示
          let statusText = item.status_txt || '未知状态';
          let statusClass = '';

          switch (item.status) {
            case 0:
              statusClass = 'status-pending';
              break;
            case 1:
              statusClass = 'status-confirmed';
              break;
            case 2:
              statusClass = 'status-completed';
              break;
            case 3:
              statusClass = 'status-cancelled';
              break;
            default:
              statusClass = 'status-unknown';
          }

          return {
            ...item,
            id: item.id,
            statusText: statusText,
            statusClass: statusClass,
            formattedDate: item.appointment || '未设置日期',
            studentName: item.user_name,
            subject: item.subjects === 1 ? '理科' : '文科',
            score: item.grades || '未填写',
            createTime: item.created_at
          };
        });

        // 更新列表数据
        const currentList = this.data.currentPage === 1 ? [] : this.data.appointmentList;
        const updatedList = [...currentList, ...formattedList];

        this.setData({
          appointmentList: updatedList,
          loading: false,
          noData: updatedList.length === 0,
          hasMore: updatedList.length < total,
          currentPage: this.data.currentPage + 1
        });
      } else {
        this.setData({
          loading: false,
          hasMore: false
        });
        wx.showToast({
          title: '获取预约列表失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取预约列表错误:', err);
      wx.hideLoading();
      this.setData({
        loading: false,
        hasMore: false
      });
      wx.showToast({
        title: '网络错误，请稍后重试',
        icon: 'none'
      });
    });
  },

  // 跳转到预约详情页面
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/my-appointments/detail/detail?id=${id}`
    });
  },

  // 取消预约
  cancelAppointment(e) {
    e.stopPropagation(); // 阻止事件冒泡，防止触发列表项点击事件
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消该预约吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '取消中...',
          });
          // 调用取消预约API
          put(`/user/cancel_reservation?r_id=${id}`).then(res => {
            wx.hideLoading();

            if (res && res.code === 200) {
              wx.showToast({
                title: '取消成功',
                icon: 'success'
              });

              // 刷新列表
              this.setData({
                currentPage: 1,
                appointmentList: [],
                hasMore: true
              });
              this.getAppointmentList(true);
            } else {
              wx.showToast({
                title: res.msg || '取消失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('取消预约错误:', err);
            wx.hideLoading();
            wx.showToast({
              title: '网络错误，请稍后重试',
              icon: 'none'
            });
          });
        }
      }
    });
  },

  // 删除预约记录
  deleteAppointment(e) {
    e.stopPropagation(); // 阻止事件冒泡，防止触发列表项点击事件
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '提示',
      content: '确定要删除该预约记录吗？删除后无法恢复',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });

          // 调用删除预约API
          del(`/user/del_reservation?r_id=${id}`).then(res => {
            wx.hideLoading();

            if (res && res.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });

              // 刷新列表
              this.setData({
                currentPage: 1,
                appointmentList: [],
                hasMore: true
              });
              this.getAppointmentList(true);
            } else {
              wx.showToast({
                title: res.msg || '删除失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('删除预约错误:', err);
            wx.hideLoading();
            wx.showToast({
              title: '网络错误，请稍后重试',
              icon: 'none'
            });
          });
        }
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      currentPage: 1,
      appointmentList: [],
      hasMore: true
    });
    this.getAppointmentList(false);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore) {
      this.getAppointmentList(false);
    }
  },

  // 跳转到预约页面
  navigateToAppointment() {
    wx.navigateTo({
      url: '/pages/appointment/appointment'
    });
  }
}) 